package com.itheima.security;

import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    //根据用户名查询数据库获取用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //username 是前台登录是从表单中获取的username
            //根据username 查询数据
        User user = userService.findByUsername(username);
        if (user == null){  //就证明不存在 返回null
            return null;
        }


        List<GrantedAuthority> list = new ArrayList<>();

        //查找到了就动态为当前用户授权
            //获取角色
        Set<Role> roles = user.getRoles();
        if(roles != null && roles.size() > 0){
            for (Role role : roles) {
                //一个用户有可能会有很多角色，循环添加角色
                list.add(new SimpleGrantedAuthority(role.getKeyword()));
                //一个角色里有很多权限 循环添加权限
                //过去角色下的权限
                Set<Permission> permissions = role.getPermissions();
                for (Permission permission : permissions) {
                    //遍历权限集合，为用户授权
                    list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                }
            }
        }

        org.springframework.security.core.userdetails.User security = new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),list);
        return security;
    }
}
